package cn.hx.admin.controller;

import cn.hx.admin.entity.Post;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;

@RestController
@CrossOrigin
public class PublicController {
    @Resource(name = "kaptchaBeanMathText")
    private Producer captchaProducer;

    @Resource(name = "kaptchaBeanMath")
    private Producer captchaProducerMath;

    Map<String, String> captchaMap = new HashMap<>();
    @Value("${captchaType}")
    private String captchaType;
    @GetMapping("captchaImage")
    public ResponseEntity<Map<String,Object>> captchaImage() throws IOException {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");

        String code = null;
        BufferedImage image = null;
        // 生成验证码
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            String capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            String capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }
        captchaMap.put(uuid,code);
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        ImageIO.write(image, "jpg", os);
        return ResponseEntity.ok(Map.of("uuid",uuid,"image", "data:image/jpg;base64," +  Base64.getEncoder().encodeToString(os.toByteArray()) ));
    }

    public ResponseEntity<String> login(String uuid,
                                        String username,
                                        String  password,
                                        String verifyCode){
        String o = captchaMap.get(uuid);
        if (o.equals(verifyCode)){
            //查询数据库校验用户名密码是否正确
        }else {
            throw new RuntimeException("验证码错误");
        }
        return null;
    }
}
